
var express = require('express');
var app = express();
const session = require('express-session');

var bodyParser = require('body-parser');
const connection = require('../tools/db'); // 获取连接实例

app.set('trust proxy', 1);
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// app.use(cookieParser)

// 导入 session 中间件
app.use(
  session({
    name: 'session_id', //默认connect.sid
    secret: 'itheima',
    resave: false,
    saveUninitialized: true,
    cookie: { // 全局设置cookie,就是访问随便api就会设置cookie，也可以在登录的路由下单独设置
      domain:'127.0.0.1',
      maxAge: 1000 * 30 * 60, //过期时间(毫秒
      httpOnly: true // 是否允许客户端修改cookie,(默认true 不能被修改)
          // secure: true //https这样的情况才可以访问cookie,默认false(推荐)
    },
  // rolling: true //在每次请求时强行设置 cookie，这将重置 cookie 过期时间(默认：false推荐false)
  })
)

// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// const router = express.Router()
// // 要在配置后使用
// app.use(router);
// router.get('/ok', (req, res) => {
//     console.log('ok');
//     // 设置相应头 设置允许跨域
//     // res.setHeader('Access-Control-Allow-Origin','http://127.0.0.1:8082')
//     res.header('Access-Control-Allow-Credentials',true);  //允许携带cookies
//     req.session.userinfo = req.body // 用户的信息
//     req.session.islogin = true // 用户的登录状态
//     console.log('ok:'+req.session.islogin);
//     res.redirect('http://127.0.0.1:8080/index.html')
//     // res.location('http://127.0.0.1:8080/index.html')
//   });
  

app.post('/api/register',urlencodedParser, function(req, res) {
  // 设置相应头 设置允许跨域
  res.setHeader('Access-Control-Allow-Origin','http://127.0.0.1:8082')
  res.setHeader('Access-Control-Allow-Credentials',true);  //允许携带cookies
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  // 判断数据库里是否已经存在该用户名,如果没有则注册，如果有则提示重新注册
  const sqlStr = 'SELECT * FROM user_msg'

  connection.query(sqlStr, (err, results) => {
  // 查询数据失败
  if (err) {
      return console.log(err.message)
  } else {
      let userData = results.map(item => item.userphone)
      let username = results.map(item => item.username)
      // 判断注册的账号是否与数据库里的账号相同 -1 代表数据库里不存在此数据
      if (userData.indexOf(req.body.userphone) == -1 && username.indexOf(req.body.username) == -1) {
          const sqlStr = `insert into user_msg(username,userphone,userpassword) values(?,?,?)`
          connection.query(sqlStr, [req.body.username, req.body.userphone, req.body.userpassword], (err, results) => {
          // 查询数据失败
          if (err) {
              return console.log(err.message)
          } else {
              res.send({
                  status: 200,
                  message: '注册成功'
              })
          }
          })
      } else if(username.indexOf(req.body.username) >= 0){
        res.send({
            status: 403,
            message: '用户名已经注册！'
        })
      }else if(userData.indexOf(req.body.userphone) >= 0){
          res.send({
              status: 402,
              message: '手机号已经注册！'
          })
      }
  }
  })
})

//获取当前时间
function getNowDate() {
  var myDate = new Date;
  var year = myDate.getFullYear(); //获取当前年
  var mon = myDate.getMonth() + 1; //获取当前月
  var date = myDate.getDate(); //获取当前日
  var hours = myDate.getHours(); //获取当前小时
  var minutes = myDate.getMinutes(); //获取当前分钟
  var seconds = myDate.getSeconds(); //获取当前秒
  var now = year + "-" + mon + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
  return now;
}


app.post('/api/login', urlencodedParser,
 function(req, res) {
  // 设置相应头 设置允许跨域
  res.setHeader('Access-Control-Allow-Origin','http://127.0.0.1:8082')
  res.setHeader('Access-Control-Allow-Credentials',true);  //允许携带cookies
  res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  const sqlStr = 'SELECT * FROM user_msg where username like ? or userphone like ?;'
  connection.query(sqlStr,[req.body.username, req.body.userphone], (err, results) => {
    // 查询数据失败
    if (err) return console.log(err.message)
    // 查询数据成功
    // 注意：如果执行的是 select 查询语句，则执行的结果是数组
    let userData = results.map(item => item.username)
    let phoneData = results.map(item => item.userphone)
    let pwdData = results.map(item => item.userpassword)

    const sql_log = 'insert into login_log(user_account,login_state,state_msg,login_time) values(?,?,?,?)'
    arr_log = []

    if (userData.indexOf(req.body.username) == -1 && phoneData.indexOf(req.body.userphone) == -1) {
      res.send({
          status: 400,
          message: '该用户不存在',
      })
      arr_log = [req.body.username, '400', '该用户不存在！', getNowDate()]
    } else {
      // 用户存在，判断密码
      if (req.body.userpassword == pwdData[0]) {
          req.session.userinfo = req.body // 用户的信息
          req.session.islogin = true // 用户的登录状态
          res.send({
              status: 200,
              message: '登录成功',
              account: req.body.username,
              islogin: true
          })
          arr_log = [req.body.username, '200', '登录成功！', getNowDate()]
      } else {
          res.send({
              status: 401,
              message: '登录失败,密码不正确',
          })
          arr_log = [req.body.username, '400', '登录失败，密码不正确！', getNowDate()]
      }
    }
    connection.query(sql_log, arr_log, (err, results) => {
        // 查询数据失败
        if (err) {
            return console.log(err.message)
        } else {
            console.log("日志存储成功！");
        }
    })

  }) 
})
 
// 获取用户姓名的接口
app.post('/api/username',urlencodedParser, (req, res) => {
  // 设置相应头 设置允许跨域
  res.setHeader('Access-Control-Allow-Origin','http://127.0.0.1:8082')
  res.setHeader('Access-Control-Allow-Credentials',true);  //允许携带cookies
  res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  if (!req.session.islogin) {
    return res.send({ status: 1, msg: 'fail' })
  }
  res.send({
    status: 0,
    msg: 'success',
  })
})

var server = app.listen(8088, function () {

  console.log("数据后台接入已准备就绪，访问地址为 http://127.0.0.1:8088")
 
})